package com.tronsis.distribution.fragment.deliver;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.order.DeliverDetailActivity;
import com.tronsis.distribution.bean.DeliveryBean;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的发货 (待发货/已发货)
 *
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class DeliverFragment extends BaseFragment {

    @BindView(R.id.rv)
    RecyclerView mRv;

    @BindView(R.id.srl)
    SwipeRefreshLayout mSrl;


    private List<DeliveryBean> mDataList = new ArrayList<>();
    private String mState;

    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;

    public static DeliverFragment create(String state) {
        Bundle bundle = new Bundle();
        bundle.putString("state", state);
        DeliverFragment fragment = new DeliverFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.layout_refresh_list, null);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        initRv();

        Bundle bundle = getArguments();
        if (bundle != null) {
            mState = bundle.getString("state");
            httpGetList(mPage, mSize, true);
        }
    }

    private void initRv() {
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);

        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpGetList(mPage = 1, mSize = 15, true);
            }
        });

        CommonAdapter adapter = new CommonAdapter<DeliveryBean>(getContext(), mDataList, R.layout.item_deliver_wait) {
            @Override
            protected void convert(ViewHolder holder, DeliveryBean deliveryBean, int position) {
                holder.setText(R.id.tv_order_num, deliveryBean.getCode());
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(deliveryBean.getStateOn()));
                holder.setText(R.id.tv_count, getString(R.string.format_count, deliveryBean.getTotalItem()));

                DeliveryBean.ReceiverAddrBean receiverAddr = deliveryBean.getReceiverAddr();
                if (receiverAddr != null) {
                    holder.setText(R.id.tv_name, getString(R.string.format_deliver_name, receiverAddr.getName()));
                    holder.setText(R.id.tv_phone, receiverAddr.getPhone());
                    holder.setText(R.id.tv_address, CommonUtil.getRegionString(receiverAddr.getRegion()) + receiverAddr.getDetail());
                }

            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, DeliverDetailActivity.class);
                intent.putExtra("DeliveryBean", mDataList.get(position));
                startActivity(intent);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(adapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    httpGetList(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRv.addItemDecoration(decoration);
        mRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mRv.setAdapter(mLoadMoreWrapper);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.MY_DELIVER_ORDER_LIST:
                httpGetList(mPage = 1, mSize = 15, true);
                break;
            default:
                break;
        }
    }

    private void httpGetList(int page, int size, final boolean isRefresh) {
        try {
            OrderBizFactory.createBiz().getDeliveryList(getActivity(), page, size, mState, new UICallBack() {
                @Override
                public void onStart() {
                    if (isRefresh) {
                        mSrl.setRefreshing(true);
                    }
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<DeliveryBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);

                }
            });
        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }


}
